from flask import Flask, request, jsonify
from flask_restful import Api, Resource
import mysql.connector
from flask_cors import CORS

app = Flask(__name__)
api = Api(app)
CORS(app)

# 数据库连接配置
db_config = {
    'host': 'localhost',
    'user': 'root',
    'port': 3307,
    'password': '123456',
    'database': 'bookschema'
}

# 创建数据库连接
db_connection = mysql.connector.connect(**db_config)
cursor = db_connection.cursor()

# 创建消息表
cursor.execute("""
CREATE TABLE IF NOT EXISTS messages (
    id INT AUTO_INCREMENT PRIMARY KEY,
    sender ENUM('admin', 'user') NOT NULL,
    recipient ENUM('admin', 'user') NOT NULL,
    content TEXT NOT NULL,
    timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
""")
db_connection.commit()

class MessageResource(Resource):
    def post(self, sender):
        # 发送消息
        data = request.get_json()
        recipient = 'admin' if sender == 'user' else 'user'
        content = data.get('content')

        # 存储消息到数据库
        cursor.execute("""
        INSERT INTO messages (sender, recipient, content) VALUES (%s, %s, %s)
        """, (sender, recipient, content))
        db_connection.commit()

        return jsonify({'status': 'Message sent'})

    def get(self, sender):
        # 读取消息
        recipient = 'admin' if sender == 'user' else 'user'
        cursor.execute("""
        SELECT content, timestamp FROM messages WHERE sender = %s AND recipient = %s
        """, (recipient, sender))
        messages = cursor.fetchall()

        # 将查询结果转换为字典列表
        messages_list = []
        for message in messages:
            messages_list.append({
                'content': message[0],
                'timestamp': message[1].strftime('%Y-%m-%d %H:%M:%S')
            })

        return jsonify({'messages': messages_list})

# 将资源添加到 API 中
api.add_resource(MessageResource, '/admin/messages', '/user/messages')

if __name__ == '__main__':
    app.run(debug=True)
